package websocket

import (
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
)

// LoginController 用户登录
func LoginController(client *Client, req *request) {
	// 从请求中获取userId
	userId := gconv.Uint64(req.Data["userId"])
	
	// 如果userId为0，可能需要处理错误情况
	if userId == 0 {
		fmt.Println("Login failed: invalid user id")
		client.SendMsg(&WResponse{
			Event: Login,
			Data: map[string]interface{}{
				"error": "invalid user id",
			},
		})
		return
	}

	fmt.Println("LoginController: userId:", userId)

	// 用户登录
	login := &login{
		UserId: userId,
		Client: client,
	}
	clientManager.Login <- login
}

func IsAppController(client *Client) {
	client.isApp = true
}

// JoinController 加入
func JoinController(client *Client, req *request) {
	name := gconv.String(req.Data["name"])

	if !client.tags.Contains(name) {
		client.tags.Append(name)
	}
	client.SendMsg(&WResponse{
		Event: Join,
		Data:  client.tags.Slice(),
	})
}

// QuitController 退出
func QuitController(client *Client, req *request) {
	name := gconv.String(req.Data["name"])
	if client.tags.Contains(name) {
		client.tags.RemoveValue(name)
	}
	client.SendMsg(&WResponse{
		Event: Quit,
		Data:  client.tags.Slice(),
	})
}

func PingController(client *Client) {
	currentTime := uint64(gtime.Now().Unix())
	client.Heartbeat(currentTime)
}

// MessageController 处理消息事件

// MessageController 处理消息事件
func MessageController(client *Client, req *request) {
    // 在这里实现处理消息的逻辑
    fmt.Printf("Received message: %+v\n", req.Data)

    // 构造广播消息
    broadcastMessage := &WResponse{
        Event: "message",
        Data:  req.Data,
    }

    // 发送到 clientManager 的 Broadcast 通道中
    select {
    case clientManager.Broadcast <- broadcastMessage:
        // 成功发送
        fmt.Println("Broadcast message sent successfully")
    default:
        fmt.Println("Broadcast channel is full or unbuffered")
    }
}




// PrivateMessageController 私聊消息控制器
func PrivateMessageController(client *Client, req *request) {
	targetUserId := gconv.Uint64(req.Data["targetUserId"])
	content := gconv.String(req.Data["content"])
	
	if targetUserId == 0 {
		client.SendMsg(&WResponse{
			Event: "error",
			Data: map[string]interface{}{
				"message": "无效的目标用户ID",
			},
		})
		return
	}
	
	// 发送私聊消息给目标用户
	privateMessage := &WResponse{
		Event: "private_message",
		Data: map[string]interface{}{
			"fromUserId": client.UserId,
			"fromClientId": client.ID,
			"content": content,
			"timestamp": gtime.Now().Unix(),
		},
	}
	
	SendToUser(targetUserId, privateMessage)
	
	// 给发送者发送确认消息
	client.SendMsg(&WResponse{
		Event: "message_sent",
		Data: map[string]interface{}{
			"status": "success",
			"targetUserId": targetUserId,
			"content": content,
		},
	})
}

// RoomMessageController 房间消息控制器
func RoomMessageController(client *Client, req *request) {
	roomName := gconv.String(req.Data["roomName"])
	content := gconv.String(req.Data["content"])
	
	if roomName == "" {
		client.SendMsg(&WResponse{
			Event: "error",
			Data: map[string]interface{}{
				"message": "房间名不能为空",
			},
		})
		return
	}
	
	// 检查用户是否在该房间中
	if !client.tags.Contains(roomName) {
		client.SendMsg(&WResponse{
			Event: "error",
			Data: map[string]interface{}{
				"message": "您不在该房间中",
			},
		})
		return
	}
	
	// 发送房间消息
	roomMessage := &WResponse{
		Event: "room_message",
		Data: map[string]interface{}{
			"roomName": roomName,
			"fromUserId": client.UserId,
			"fromClientId": client.ID,
			"content": content,
			"timestamp": gtime.Now().Unix(),
		},
	}
	
	SendToTag(roomName, roomMessage)
	
	// 给发送者发送确认消息
	client.SendMsg(&WResponse{
		Event: "room_message_sent",
		Data: map[string]interface{}{
			"status": "success",
			"roomName": roomName,
			"content": content,
		},
	})
}

// BroadcastMessageController 广播消息控制器
func BroadcastMessageController(client *Client, req *request) {
	content := gconv.String(req.Data["content"])
	
	if content == "" {
		client.SendMsg(&WResponse{
			Event: "error",
			Data: map[string]interface{}{
				"message": "消息内容不能为空",
			},
		})
		return
	}
	
	// 发送广播消息
	broadcastMessage := &WResponse{
		Event: "broadcast_message",
		Data: map[string]interface{}{
			"fromUserId": client.UserId,
			"fromClientId": client.ID,
			"content": content,
			"timestamp": gtime.Now().Unix(),
		},
	}
	
	SendToAll(broadcastMessage)
	
	// 给发送者发送确认消息
	client.SendMsg(&WResponse{
		Event: "broadcast_sent",
		Data: map[string]interface{}{
			"status": "success",
			"content": content,
		},
	})
}

// ClientMessageController 客户端定向消息控制器
func ClientMessageController(client *Client, req *request) {
	targetClientId := gconv.String(req.Data["targetClientId"])
	content := gconv.String(req.Data["content"])
	
	if targetClientId == "" {
		client.SendMsg(&WResponse{
			Event: "error",
			Data: map[string]interface{}{
				"message": "目标客户端ID不能为空",
			},
		})
		return
	}
	
	// 发送定向消息给特定客户端
	clientMessage := &WResponse{
		Event: "client_message",
		Data: map[string]interface{}{
			"fromUserId": client.UserId,
			"fromClientId": client.ID,
			"content": content,
			"timestamp": gtime.Now().Unix(),
		},
	}
	
	SendToClientID(targetClientId, clientMessage)
	
	// 给发送者发送确认消息
	client.SendMsg(&WResponse{
		Event: "client_message_sent",
		Data: map[string]interface{}{
			"status": "success",
			"targetClientId": targetClientId,
			"content": content,
		},
	})
}